// sub_jigouguanli/jigouedit/jigouedit.js
import des from "../../utils/des";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: "",
    form: {
      personName: "",
      personPhone: "",
      beBank: "",
      beBranch: "",
      beBranchId: "",
      personRole: "",
      BankToolCode: "--",
      isBankjoint: false,
      BankjointType: ["1", "2"],
      ToolImg: "",
      classify: []
    },
    beBankId: "",
    // https://zx-1311146360.cos.ap-shanghai.myqcloud.com/personalCenter/1.png
    // 所在银行
    beBankIshow: false,
    beBankArr: ["城市商业银行", "村镇银行", "股份制商业银行", "国有大型银行", "金融租赁公司", "开发性金融机构", "农村商业银行", "企业集团财务公司", "外资银行", "消费金融公司", "信托公司", "政策性银行"],

    // 所属分支行
    beBranchIshow: false,
    beBranchArr: ["--"],
    beBranchId: "",
    beBranchIndex: "",
    // 用户角色
    personRoleIsshow: false,
    personRoleArr: [],
    personRole1Arr: ["一级管理员", "二级管理员", "客户经理"],
    personRole2Arr: ["二级管理员", "客户经理"],
    personRoleIndex: 3,
    // 名片/工牌信息
    fileList: []
  },
  // sec_admin 二级
  // cbrc 银监
  // fir_admin 一级
  // manager 客户经理

  // 5e64 bad081eb469d941a9d013c92f778 sec_admin 二级
  // 5 f9ba2b81904481fb1fa9fe88bb3511a cbrc 银监
  // 61 ebf3fd651e49618b7235be3051d9d1 fir_admin 一级
  // F48FABCC550348C9E053541012AC6AFB manager 客户经理
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(options);
    if (options.id) {
      this.setData({
        userId: options.id
      })
    }
    this.getUserInfo()
    // 获取所属分支行列表
    // getApp().globalData.request(
    //   "/corpVisit/getOrganizationList", {},
    //   "POST"
    // ).then(res => {
    //   console.log(res);
    //   res.data.unshift({
    //     name: "--",
    //     organizationId: "0"
    //   })
    //   this.setData({
    //     beBranchArr: res.data
    //   })
    //   if (this.data.beBranchId !== "") {
    //     this.data.beBranchArr.forEach((item, index) => {
    //       if (item.organizationId == this.data.beBranchId) {
    //         this.setData({
    //           ['form.beBranch']: item.name,
    //           beBranchIndex: index * 1
    //         })
    //       }
    //     })
    //   }
    // })
  },

  getUserInfo () {
    let prams = {
      userId: this.data.userId
    }
    console.log(prams);
    getApp().globalData.request('/corpVisit/query_user_info', prams, "POST",).then(res => {
      console.log(res);
      this.setData({
        ['form.personName']: res.data.name,
        ['form.personPhone']: res.data.phone,
        ['form.beBank']: res.data.bankInfo.branchBank,
        ['form.beBranch']: res.data.bankInfo.bankName,
        ['form.beBranchId']: res.data.bankInfo.bankId,
        ['form.personRole']: this.filterRoles(res.data.roles),
        ['form.BankToolCode']: res.data.jobNumber,
        ['form.isBankjoint']: res.data.isParticipate == "0" ? false : true,
        ['form.BankjointType']: this.filterBankjointType(res.data.visitType),
        // serInfo.visitType == 1?'企业':userInfo.visitType == 2?'个体户':'全部'
        ['form.ToolImg']: res.data.jobCardUrl,
        ['form.classify']: this.convertStringToArray(res.data),
        beBankId: res.data.bankInfo.branchBankId,
        // fileList: [{
        //   url: res.data.jobCardUrl,
        //   name: "图片1"
        // }]
      })
      if (res.data.jobCardUrl) {
        this.setData({
          fileList: [{
            url: res.data.jobCardUrl,
            name: "图片1"
          }]
        })
      }
      if (this.filterRoles(res.data.roles) == "一级管理员") {
        this.setData({
          personRoleArr: this.data.personRole1Arr
        })
      } else {
        this.setData({
          personRoleArr: this.data.personRole2Arr
        })
      }
    })
  },

  // methed
  // sec_admin 二级
  // cbrc 银监
  // fir_admin 一级
  // manager 客户经理
  filterRoles (arr) {
    var str = ""
    if (arr.length > 0) {
      switch (arr[0].roleName) {
        case "fir_admin":
          str = "一级管理员"
          break;
        case "manager":
          str = "客户经理"
          break
        case "sec_admin":
          str = "二级管理员"
          break
        default:
          break;
      }
    } else {
      str = ""
    }

    return str
  },
  filterBankjointType (str) {
    let arr = []
    switch (str) {
      case '1':
        arr = ["1"]
        break;
      case '2':
        arr = ["2"]
        break;
      case '3':
        arr = ["1", '2']
        break;
      default:
        break;
    }
    return arr
  },
  // 5e64 bad081eb469d941a9d013c92f778 sec_admin 二级
  // 5 f9ba2b81904481fb1fa9fe88bb3511a cbrc 银监
  // 61 ebf3fd651e49618b7235be3051d9d1 fir_admin 一级
  // F48FABCC550348C9E053541012AC6AFB manager 客户经理
  filterRoleId (name) {
    let arr = []
    switch (name) {
      case '一级管理员':
        arr = ["F48FABCC550248C9E053541012AC6AFB"]
        break;
      case '二级管理员':
        arr = ["F48FABCC550048C9E053541012AC6AFB"]
        break;
      case '客户经理':
        arr = ["F48FABCC550348C9E053541012AC6AFB"]
        break;
      default:
        break;
    }
    return arr
  },
  filterBankjointTypeArr (arr) {
    let str = ""
    console.log(arr);
    switch (arr.length) {
      case 0:
        str = ''
        break;
      case 1:
        str = arr[0]
        break;
      case 2:
        str = '3'
        break;
      default:
        break;
    }
    return str
  },
  setpersonName (e) {
    this.setData({
      ["form.personName"]: e.detail.value
    })
  },
  setpersonPhone (e) {
    this.setData({
      ["form.personPhone"]: e.detail.value
    })
  },
  setBankToolCode (e) {
    this.setData({
      ["form.BankToolCode"]: e.detail.value
    })
  },

  // 所在银行
  beBankIshow () {
    this.setData({
      beBankIshow: true
    })
  },
  beBankConfirm (e) {
    this.setData({
      ["form.beBank"]: e.detail.value,
      beBankIshow: false,
    });
  },
  beBankCancel () {
    this.setData({
      beBankIshow: false,
    });
  },
  //所属分支行
  beBrancheShow () {
    wx.navigateTo({
      url: `/sub_renyuanguanli/bankList/bankList?id=${this.data.beBankId}`,
    })
    // this.setData({
    //   beBranchIshow: true,
    // });
  },
  beBranchConfirm (e) {
    console.log(e);
    this.setData({
      ["form.beBranch"]: e.detail.value.name,
      beBranchId: e.detail.value.organizationId,
      beBranchIshow: false,
    });
  },
  beBranchCancel () {
    this.setData({
      beBranchIshow: false,
    });
  },
  // 用户角色
  personRoleShow () {
    this.setData({
      personRoleIsshow: true,
    });
  },
  personRoleConfirm (e) {
    console.log(e);
    this.filterRoleId(e.detail.value)
    this.setData({
      ["form.personRole"]: e.detail.value,
      personRoleIsshow: false,
    });
  },
  personRoleCancel () {
    this.setData({
      personRoleIsshow: false,
    });
  },
  // 是否银企对接
  isBankjointChange (e) {
    this.setData({
      ['form.isBankjoint']: e.detail,
      ['form.classify']: e.detail ? this.data.form.classify : []
    });
  },
  convertStringToArray (str) {
    if (str.isParticipate === '0' || str.isParticipate === '1') {
      return []
    } else {
      return str.isParticipate.split(',')
    }
  },
  filterClassify (arr) {
    if (arr.length === 0 && arr[0] === "0") {
      return arr;
    } else {
      arr.sort(function (a, b) {
        return parseInt(a) - parseInt(b);
      });
    }
    return arr;
  },

  typeChange (e) {
    // this.filterClassify(e.detail)
    if (e.detail.length === 0) {
      e.detail = ["0"]
    } else {
      e.detail = e.detail.filter(item => item !== "0")
    }
    // console.log(e.detail);
    this.setData({
      ['form.classify']: e.detail
    })
  },
  // 走访企业
  BankjointTypeChange (e) {
    this.filterBankjointTypeArr(e.detail)
    this.setData({
      ['form.BankjointType']: e.detail
    })
  },
  deleteImg () {
    this.data.fileList.pop()
    this.setData({
      fileList: this.data.fileList,
    })
    getApp().globalData.request("/api/fileApi/cosDelete", {
      url: this.data.form.ToolImg
    }, "POST").then(res => {
      console.log(res);
      if (res.code == 200) {
        this.setData({
          ["form.ToolImg"]: ""
        })
        wx.showToast({
          title: res.data,
        })
      } else {
        wx.showToast({
          title: res.data,
        })
      }
    })
  },
  selectImg () {
    var that = this
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      sizeType: ['original', 'compressed'],
      success (res) {
        console.log(res);
        const tempFilePaths = res.tempFiles
        that.data.fileList.push({
          ...tempFilePaths[0],
          url: tempFilePaths[0].tempFilePath,
          deletable: true,
        })
        that.setData({
          fileList: that.data.fileList,
          islodding: true
        })
        // 上传文件 
        wx.showLoading({
          title: '上传中',
        })
        wx.uploadFile({
          url: 'https://fintech-wx.szjrgzjg.com/api/fileApi/cosUpload',
          filePath: tempFilePaths[0].tempFilePath,
          name: 'file',
          formData: {
            file: tempFilePaths[0],
            folder: "mini_renyuanguanli"
          },
          header: {
            token: wx.getStorageSync("token")
          },
          success (res) {
            var data = des.decrypt(
              JSON.parse(res.data).data,
              "98fbffd1064a4355b8abaacb6fa96f94"
            );
            console.log(JSON.parse(data));
            wx.hideLoading()
            that.setData({
              ["form.ToolImg"]: JSON.parse(data).data,
              fileList: [{
                url: JSON.parse(data).data,
                name: "图片1"
              }],
              islodding: false
            })
          },
          fail (err) {
            console.log(err);
          }
        })
      }
    })
  },
  // 点击删除
  deleteRenyuan () {
    getApp().globalData.request(
      "/user/delete_batch", [this.data.userId],
      "POST"
    ).then(res => {
      if (res.code == 200) {
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 3];
        prevPage.setData({ // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
          refresh: true,
          list: [],
          pageNum: 1,
          isManage: false,
          ischecked: false,
        })
        wx.navigateBack({
          delta: 2 // 返回上一级页面。
        })
      }

    })
  },
  // 点击修改
  editRenyuan () {
    console.log(this.data.form);
    for (const key in this.data.form) {
      // console.log(key);
      // console.log(this.data.form[key]);
      if (key !== 'ToolImg' && key !== "isBankjoint" && key !== "classify") {
        if (this.data.form[key] == "") {
          wx.showToast({
            title: '请先完善信息',
            icon: "none"
          })
          return
        } else {

        }
      }
    }
    let params = {
      "userId": this.data.userId,
      "name": this.data.form.personName,
      "phone": this.data.form.personPhone,
      "agencyCode": this.data.form.beBranchId,
      "roles": this.filterRoleId(this.data.form.personRole),
      // "classify": this.data.form.classify,
      "jobNumber": this.data.form.BankToolCode,
      "visitType": this.filterBankjointTypeArr(this.data.form.BankjointType),
      "jobCardUrl": this.data.form.ToolImg,
    }
    // 处理用户标签
    if (this.data.form.isBankjoint) {
      params.isParticipate = this.data.form.classify.length > 0 ? this.data.form.classify.join(',') : '1'
    } else {
      params.isParticipate = '0'
    }
    console.log(params, "修改提交的参数");
    getApp().globalData.request(
      "/user/update", params,
      "POST"
    ).then(res => {
      console.log(res);
      if (res.code == 200) {
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 3];
        prevPage.setData({ // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
          refresh: true
        })
        wx.navigateBack({
          delta: 2 // 返回上一级页面。
        })
      } else {
        wx.showToast({
          title: '该手机号已注册',
          icon: 'none'
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {

  }
})